package com.ly.code;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.sql.DataSource;

@Configuration
@ComponentScan("com.ly.code")
//@EnableTransactionManagement
public class CodeApp implements WebMvcConfigurer {

    @Value("${ly.code.url}")
    private String url;
    @Value("${ly.code.username}")
    private String username;
    @Value("${ly.code.password}")
    private String password;
    @Value("${ly.code.driver}")
    private String driver;
    @Value("${ly.code.save-path}")
    private String savePath;

    @Bean
    JdbcTemplate codeJdbcTemplate() {
        DriverManagerDataSource ds = new DriverManagerDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        return new JdbcTemplate(ds);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String path = (savePath.startsWith("/") ? "" : "/") + savePath + (savePath.endsWith("/") ? "" : "/");
        registry.addResourceHandler("/code/down/**")
                .addResourceLocations("file:" + path);
    }
}
